package com.gitee.wsl.task


//import java.util.concurrent.ConcurrentLinkedQueue
//import java.util.concurrent.ForkJoinPool
//
//https://juejin.cn/post/7474273971878346788

//internal class TimeWheel(
//    //每个槽位所代表的时间/时间间隔（毫秒）;
//    private val tickDuration: Long,
//    private val wheelSize: Int,
//) {
//    private val buckets = ArrayList<ConcurrentLinkedQueue<Task<*, *>?>>(this.wheelSize) //时间轮槽位;
//    private var currentTick = 0 //当前槽位指针;
//    private var higherTimeWheel: TimeWheel? = null
//    private var lowerTimeWheel: TimeWheel? = null
//
//    init {
//        for (i in 0..<this.wheelSize) {
//            buckets.add(ConcurrentLinkedQueue<Task<*, *>?>())
//        }
//    }
//
//    fun setHigherTimeWheel(higherTimeWheel: TimeWheel?) {
//        this.higherTimeWheel = higherTimeWheel
//    }
//
//    fun setLowerTimeWheel(lowerTimeWheel: TimeWheel?) {
//        this.lowerTimeWheel = lowerTimeWheel
//    }
//
//    fun addTask(task: Task<*, *>) {
//        val now = System.currentTimeMillis()
//        val delay: Long = task.getScheduleTime() - now
//        //延时时间小于零立即执行
//        if (delay <= 0) {
//            ForkJoinPool.commonPool().execute(task.getJob())
//        } else if (delay < tickDuration * wheelSize) { //延时时间在当前时间轮范围内，将任务添加到当前时间轮中;
//            val targetTick = (currentTick + (delay / tickDuration).toInt()) % wheelSize
//            buckets.get(targetTick).add(task)
//        } else { //延时时间不在当前时间轮范围内，尝试向上级时间轮委派任务。
//            if (higherTimeWheel != null) {
//                higherTimeWheel!!.addTask(task)
//            } else {
//                //抛出异常或者实现动态扩容
//            }
//        }
//    }
//
//    //时间轮推进
//    fun advance() {
//        val tasks = buckets.get(currentTick)
//        val it: MutableIterator<Task<*, *>> = tasks.iterator()
//        while (it.hasNext()) {
//            val task = it.next()
//            //执行到期任务
//            if (task.getScheduleTime() <= System.currentTimeMillis()) {
//                task.getJob().run()
//                it.remove()
//            } else if (lowerTimeWheel != null) {
//                //未到期任务，进行任务降级;
//                lowerTimeWheel!!.addTask(task)
//                it.remove()
//            }
//        }
//        currentTick = (currentTick + 1) % wheelSize
//        //当前时间轮转动一圈后,推动上级时间轮转动一个槽位。
//        if (currentTick == 0 && higherTimeWheel != null) {
//            higherTimeWheel!!.advance()
//        }
//    }
//}